let secret_code = ''
const app = getApp()
Page({
  data: {
    mobile: '',
    code: '',
    countDownVisible: false,
  },
  onLoad({
    redirectURL
  }) {
    // 获取地址参数
    this.setData({
      redirectURL
    })
  },
  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  verifyMobile() {
    const reg = /^[1][3-8][0-9]{9}$/
    const valid = reg.test(this.data.mobile.trim())
    if (!valid) {
      return wx.utils.toast('请填写正确的手机号码！')
    }
    return valid
  },
  async getCode() {
    if (!this.verifyMobile()) return
    const {
      code,
      data
    } = await wx.http.get('/code', {
      mobile: this.data.mobile.trim()
    })
    if (code !== 10000) {
      return wx.utils.toast('发送失败，请稍后重试！')
    }
    wx.utils.toast('发送成功，请查收短信')
    this.setData({
      countDownVisible: true
    })
    setTimeout(() => {
      this.setData({
        code: data.code
      })
    }, 3000)
    secret_code = data.code
  },
  verifyCode() {
    const reg = /^\d{6}$/
    const valid = reg.test(this.data.code.trim())
    if (!valid) {
      wx.utils.toast('请检查验证码格式是否正确！')
    }
    return valid
  },
  copyCode() {
    wx.setClipboardData({
      data: secret_code
    })
  },
  async submitForm() {
    if (!this.verifyMobile()) return
    if (!this.verifyCode()) return
    const {
      mobile,
      code
    } = this.data
    const res = await wx.http.post('/login', {
      mobile,
      code
    })
    if (res.code !== 10000) {
      return wx.utils.toast('请检查验证码是否正确！')
    }
    app.setToken(res.data.token, res.data.refreshToken)
    if (this.data.redirectURL) {
      wx.redirectTo({
        url: this.data.redirectURL,
      })
    } else {
      wx.navigateBack({
        delta: 1
      });
    }

  }
})